package com.fzj.example.thread.forkjoin;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: ForkJoinPoolDemo
 * date: 2019/11/6 10:53
 * Description: 计算1+2+3...10000
 *
 * @author fanzj@bonree.com
 * @since JDK 1.8
 */
public class ForkJoinPoolDemo {

    static class SendMsgTask extends RecursiveAction{

        private final int threshold = 10;

        private int start;

        private int end;

        private List<String> data;

        public SendMsgTask(){}

        public SendMsgTask(int start, int end, List< String > data) {
            this.start = start;
            this.end = end;
            this.data = data;
        }

        @Override
        protected void compute() {
            if(start-end<=threshold){
                for(int i=start;i<end;i++){
                    System.out.println(Thread.currentThread().getName()+":"+data.get(i));
                }
            }else{
                int middle=(start+end)/2;
                invokeAll(new SendMsgTask(middle,end,data),new SendMsgTask(start,middle,data));
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        List<String> list=new ArrayList<>();
        int i=0;
        while (i<1000000){
            list.add(String.valueOf(i+1));
            i++;
        }
        ForkJoinPool forkJoinPool=new ForkJoinPool();
        forkJoinPool.execute(new SendMsgTask(0,list.size(),list));
        forkJoinPool.awaitTermination(100, TimeUnit.SECONDS);
        forkJoinPool.shutdown();
    }

}
